package com.sora.sys.service.impl;

import com.sora.sys.domain.Role;
import com.sora.sys.mapper.RoleMapper;
import com.sora.sys.service.IRoleService;
import com.sora.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void save(Role role) {
        super.save(role);
        //角色添加之后才有自增长的role_id
        //添加角色菜单的中间表数据
        if(role.getMenus() != null && role.getMenus().size()>0){
            roleMapper.addRoleMenusByRoleId(role.getId(),role.getMenus());
        }
        //添加角色权限的中间表数据
        if(role.getPermissions() != null && role.getPermissions().size()>0){
            roleMapper.addRolePermissionsByRoleId(role.getId(),role.getPermissions());
        }
    }

    @Override
    @Transactional
    public void del(Long id) {
        //删除角色菜单的中间表数据
        roleMapper.delRoleMenuByRoleId(id);
        //删除角色权限的中间表数据
        roleMapper.delRolePermissionByRoleId(id);
        //删除角色员工的中间表数据
        roleMapper.delRoleEmployeeByRoleId(id);
        super.del(id);
    }

    @Override
    @Transactional
    public void update(Role role) {
        //删除角色菜单的中间表数据
        roleMapper.delRoleMenuByRoleId(role.getId());
        //删除角色权限的中间表数据
        roleMapper.delRolePermissionByRoleId(role.getId());

        //添加角色菜单的中间表数据
        if(role.getMenus() != null && role.getMenus().size()>0){
            roleMapper.addRoleMenusByRoleId(role.getId(),role.getMenus());
        }
        //添加角色权限的中间表数据
        if(role.getPermissions() != null && role.getPermissions().size()>0){
            roleMapper.addRolePermissionsByRoleId(role.getId(),role.getPermissions());
        }
        super.update(role);
    }

    @Override
    @Transactional
    public void batchDel(List<Long> ids) {
        for (Long id : ids) {
            del(id);
        }
    }
}
